<template>
  <div class="ant-pro-page-container-children-content">
    <pro-table
      ref="table"
      toolbar-title="工序流转卡信息"
      :row-key="rowKey"
      :request="tableRequest"
      :columns="columns"
      :scroll="{ x: 1500 }"
    >
      <!-- 查询表单 -->
      <template #search-form="searchFormState">
        <a-row :gutter="16">
          <a-col :md="4" :sm="24">
            <a-form-item label="卡号">
              <a-input v-model="searchFormState.queryParam.cardNumber" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="MO编号">
              <a-input v-model="searchFormState.queryParam.moNumber" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="物料编码">
              <a-input v-model="searchFormState.queryParam.materialCode" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item :wrapper-col="{ flex: '1 1 0' }" class="search-actions-wrapper">
              <a-space>
                <a-button type="primary" :loading="searchFormState.loading" @click="searchFormState.reloadTable(true)">
                  查询
                </a-button>
                <a-button @click="searchFormState.resetSearchForm">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </template>



      <!-- 操作按钮区域 -->
      <template #toolbar-action>
        <a-button
          v-has="'ProductionProcesses:t-process-flow-card:add'"
          type="primary"
          icon="plus"
          @click="handleAdd()"
        >获取ERP数据
        </a-button>
        <a-button
          v-has="'ProductionProcesses:t-process-flow-card:add'"
          type="primary"
          icon="plus"
          @click="handleAddByFlowCardNumber()"
        >MO编号的数据</a-button>
      </template>

      <!--表格展示相关插槽-->
      <template #action-slot="text, record">
        <!-- <a v-has="'ProductionProcesses:t-process-flow-card:edit'" @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" /> -->
        <a v-has="'ProductionProcesses:t-process-flow-card:details'" @click="handleDetails(record)">查看</a>
        <a-divider type="vertical" />
        <a v-has="'ProductionProcesses:t-process-flow-card:details'" @click="printBox(record)">打印</a>
        <!-- <a-divider type="vertical" />
            <a-popconfirm
            	v-has="'ProductionProcesses:t-process-flow-card:del'"
                title="确认要删除吗？"
                @confirm="() => handleDel(record)"
             >
              <a href="javascript:" class="ballcat-text-danger">删除</a>
            </a-popconfirm> -->

      </template>
    </pro-table>

    <!--表单弹窗-->
    <t-process-flow-card-modal-form ref="formModal" @reload-page-table="reloadPageTable" />
    <t-process-flow-card-modal-detail ref="processFlowCardDetailModal" @reload-page-table="reloadPageTable" />
    <!-- 打印始 -->
    <div id="printJS-HTML" style="display:none;">
      <print-template :print-arr="printArr"></print-template>
    </div>
    <!-- 打印终 -->
  </div>

</template>

<script>
import { message } from 'ant-design-vue'
import ProTable from '@/components/Table/ProTable.js'
import { doRequest } from '@/utils/request'
import {
  getPage,
  delObj,
  exportDetails,
  getDataFromErp,
  getDetails,
  getDataFromErpByMo
} from '@/api/ProductionProcesses/t-process-flow-card'
import TProcessFlowCardModalForm from '@/views/ProductionProcesses/t-process-flow-card/TProcessFlowCardModalForm'
import TProcessFlowCardModalDetail from '@/views/ProductionProcesses/t-process-flow-card/TProcessFlowCardModalDetail'
import printJS from 'print-js'
import 'print-js/dist/print.css'
import PrintTemplate from '@/views/ProductionProcesses/t-process-flow-card/print-template.vue' // 引入样式
import printTemplateCss from '@/styles/printTemplate.less'
import { Modal } from 'ant-design-vue';



export default {
  name: 'TProcessFlowCardPage',
  components: { ProTable, TProcessFlowCardModalForm, TProcessFlowCardModalDetail , PrintTemplate},
  data() {
    return {
      rowKey: 'id',
      tableRequest: getPage,
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: '80px',
          customRender: (text, record, index) => {
            // 从 props 或 ref 中获取分页信息
            const pagination = this.$refs.table?.localPagination || {}
            const current = pagination.current || 1
            const pageSize = pagination.pageSize || 10
            return (current - 1) * pageSize + index + 1
          }
        },
        {
          title: '卡号',
          dataIndex: 'cardNumber',
          width: '150px',
          ellipsis: true,
          customRender: (text, record) => {
            return (
              <a
                style="cursor: pointer; color: #1890ff;"
                ondblclick={() => this.$router.push({ path: '/reportingforwork', query: { flowCardNumber: record.cardNumber } })}
              >
                {text}
              </a>
            )
          }
        },
        {
          title: 'MO编号',
          dataIndex: 'moNumber',
          width: '150px',
          ellipsis: true
        },
        {
          title: '物料编码',
          dataIndex: 'materialCode',
          width: '150px',
          ellipsis: true
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: '150px',
          ellipsis: true
        },
        {
          title: '规格型号',
          dataIndex: 'specification',
          width: '200px',
          ellipsis: true
        },
        {
          title: '材质',
          dataIndex: 'materialType',
          width: '150px',
          ellipsis: true
        },
        {
          title: '表面处理',
          dataIndex: 'surfaceTreatment',
          width: '150px',
          ellipsis: true
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: '150px',
          ellipsis: true
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: '150px',
          ellipsis: true
        },
        {
          title: '计划开始时间',
          dataIndex: 'plannedStartTime',
          width: '200px',
          sorter: true
        },
        {
          title: '计划结束时间',
          dataIndex: 'plannedEndTime',
          width: '200px',
          sorter: true
        },
        {
          title: '生命周期',
          dataIndex: 'lifecycle',
          width: '150px',
        },
        // {
        //   title: '创建时间',
        //   dataIndex: 'createTime',
        //   width: '150px',
        //   sorter: true
        // },
        {
          title: '操作',
          key: 'operate',
          align: 'center',
          width: '150px',
          scopedSlots: { customRender: 'action-slot' }
        }
      ],
      printArr:[],
      flowCardNumber: ''
    }
  },
  methods: {
    /**
     *  刷新表格
     */
    reloadPageTable(withFirstPage = true) {
      this.$refs.table.reloadTable(withFirstPage)
    },
    /**
     * 新建工序流转卡信息
     */
    handleAdd() {
      // const attributes = { title: '新建工序流转卡信息' }
      // this.$refs.formModal.add(attributes)
      getDataFromErp()
    },
    /**
     * 新建工序流转卡信息
     */
    handleAddByFlowCardNumber() {
      Modal.confirm({
        title: '输入MO编号',
        content: (
          <a-input
            placeholder="请输入MO编号"
            v-model={this.flowCardNumber}
          />
        ),
        onOk: () => {
          if (!this.flowCardNumber) {
            this.$message.error('MO编号不能为空！');
            return Promise.reject();
          }
          return getDataFromErpByMo(this.flowCardNumber)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('ERP数据获取成功！');
                // 可选：刷新表格数据
                this.loadData();
              } else {
                this.$message.error(res.message || 'ERP数据获取失败');
              }
              this.flowCardNumber = '';
            })
            .catch(err => {
              this.flowCardNumber = '';
              this.$message.error('请求失败：' + err.message);
            });
        },
      });
    },
    /**
     * 编辑工序流转卡信息
     * @param record 当前工序流转卡信息属性
     */
    handleEdit(record) {
      const attributes = { title: '编辑工序流转卡信息' }
      this.$refs.formModal.update(record, attributes)
    },
    /**
     * 删除工序流转卡信息
     * @param record 当前工序流转卡信息属性
     */
    handleDel(record) {
      doRequest(delObj(record[this.rowKey]), {
        onSuccess: () => {
          this.reloadPageTable(false)
        }
      })
    },
    /**
     * 查看工序流转卡工序信息
     * @param record 当前工序流转卡信息属性
     */
    handleDetails(record) {
      const attributes = { title: '查看流程工序' }
      this.$refs.processFlowCardDetailModal.open(record)
    },
    /**
     * 导出工序流转卡工序信息
     * @param record 当前工序流转卡信息属性
     */
    async handleExport(record) {
      try {
        // 调用导出API
        const response = await exportDetails(record[this.rowKey], {
          responseType: 'blob' // 关键：指定响应类型为blob
        })

        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')

        // 从响应头获取文件名（后端需要设置Content-Disposition）
        let filename = 'export.xlsx' // 默认文件名
        const disposition = response.headers['content-disposition']
        if (disposition) {
          const filenameMatch = disposition.match(/filename=(.+)/)
          if (filenameMatch) {
            filename = decodeURIComponent(filenameMatch[1])
          }
        }

        // 设置下载属性
        link.href = url
        link.setAttribute('download', filename)
        document.body.appendChild(link)

        // 触发下载
        link.click()

        // 清理
        window.URL.revokeObjectURL(url)
        document.body.removeChild(link)
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败，请重试')
      }
    },
    handlePrint(record) {
      return new Promise((resolve, reject) => {
        getDetails(record.cardNumber).then(response => {
          const originalData = response.data;
          const records = originalData.records || [];

          // 转换数据结构，适配打印模板
          const printData = {
            cardNumber: record.cardNumber || "",
            moNumber: record.moNumber || "",
            materialCode: record.materialCode || "",
            materialName: record.materialName || "",
            specification: record.specification || "",
            materialType: record.materialType || "",
            surfaceTreatment: record.surfaceTreatment || "",
            quantity: record.quantity || "",
            unit: record.unit || "",
            plannedStartTime: record.plannedStartTime || "",
            plannedEndTime: record.plannedEndTime || "",
            lifecycle: record.lifecycle || "",
            page: [] // 分页数据
          };

          // 分页处理，每16条为一页
          for (let i = 0; i < records.length; i += 16) {
            const pageData = {
              goods: records.slice(i, i + 16).map(item => ({
                flowCardNumber: item.flowCardNumber,
                processSequence: item.processSequence,
                processCode: item.processCode,
                processName: item.processName,
                totalTimeConsumption: item.totalTimeConsumption,
                totalQuantity: item.totalQuantity,
                completedQuantity: item.completedQuantity,
                scrappedQuantity: item.scrappedQuantity,
                statusMsg: item.statusMsg
              }))
            };
            printData.page.push(pageData);
          }

          // 包装成printArr需要的格式
          this.printArr = [printData];
          console.log('格式化后的打印数据:', this.printArr);
          resolve();
        }).catch(error => {
          console.error('获取数据失败:', error);
          this.$message.error('获取数据失败，请重试');
          reject(error);
        });
      });
    },
    printBox(record) {
      // if (!this.printArr || this.printArr.length === 0) {
      //   return this.$message.warning('无可打印的数据！');
      // }
      try {
        this.handlePrint(record).then(resolve => {
          //先设置模板为可见状态

          document.querySelector('#printJS-HTML').style.display = 'block';
          // document.querySelector('#printJS-HTML').innerHTML = '';

          //这个focus事件为啥忘记了，好像是和打印的窗口有关，需要添加一下

          const focuser = setInterval(() => window.dispatchEvent(new Event('focus')), 500);

          setTimeout(function () {
            printJS({
              printable: 'printJS-HTML',
              type: 'html',
              // css: '/statics/components/printTemplate/printTemplate.css' , // 这里是模板的css样式引入即可
              style: '/* Base reset for printing */\n' +
                '@page {\n' +
                '  size: A4 portrait;\n' +
                '  margin: 0;\n' +
                '}\n' +
                '\n' +
                'body {\n' +
                '  margin: 0;\n' +
                '  padding: 0;\n' +
                '  font-family: "Microsoft YaHei", Arial, sans-serif;\n' +
                '  line-height: 1.5;\n' +
                '}\n' +
                '\n' +
                '.print-template {\n' +
                '  width: 100%;\n' +
                '  height: 100%;\n' +
                '  box-sizing: border-box;\n' +
                '}\n' +
                '\n' +
                '/* Print box styling */\n' +
                '.printBox {\n' +
                '  width: 100%;\n' +
                '  page-break-inside: avoid;\n' +
                '}\n' +
                '\n' +
                '/* Title styling - centered */\n' +
                '.printBox-title th {\n' +
                '  text-align: center;\n' +
                '  font-size: 20px;\n' +
                '  font-weight: bold;\n' +
                '  padding: 10px 0;\n' +
                '  border: none !important;\n' +
                '}\n' +
                '\n' +
                '/* Info row styling - no borders, left aligned, no wrap */\n' +
                '.printBox-info th {\n' +
                '  text-align: left;\n' +
                '  padding: 5px 8px;\n' +
                '  font-weight: normal;\n' +
                '  border: none !important;\n' +
                '  white-space: nowrap;\n' +
                '  overflow: hidden;\n' +
                '  text-overflow: ellipsis;\n' +
                '}\n' +
                '\n' +
                '/* Table styling */\n' +
                '.assetPrintTable {\n' +
                '  width: 100%;\n' +
                '  border-collapse: collapse;\n' +
                '  margin-bottom: 10px;\n' +
                '  page-break-inside: avoid;\n' +
                '}\n' +
                '\n' +
                '/* Header row with borders */\n' +
                '.m-order-list-header-wrap th {\n' +
                '  border: 1px solid #000;\n' +
                '  padding: 8px;\n' +
                '  text-align: center;\n' +
                '  background-color: #f2f2f2;\n' +
                '  font-weight: bold;\n' +
                '  white-space: nowrap;\n' +
                '}\n' +
                '\n' +
                '/* Table body cells with borders */\n' +
                '.assetPrintTable tbody td {\n' +
                '  border: 1px solid #000;\n' +
                '  padding: 8px;\n' +
                '  text-align: center;\n' +
                '  white-space: nowrap;\n' +
                '}\n' +
                '\n' +
                '/* Ensure table rows don\'t break across pages */\n' +
                '.assetPrintTable tr {\n' +
                '  page-break-inside: avoid;\n' +
                '  page-break-after: auto;\n' +
                '}\n' +
                '\n' +
                '/* Paging control */\n' +
                '.paging {\n' +
                '  page-break-after: always;\n' +
                '  height: 0;\n' +
                '  visibility: hidden;\n' +
                '}\n' +
                '\n' +
                '/* Print-specific adjustments */\n' +
                '@media print {\n' +
                '  body {\n' +
                '    margin: 0;\n' +
                '    padding: 0;\n' +
                '  }\n' +
                '  \n' +
                '  .print-template {\n' +
                '    width: 100%;\n' +
                '    margin: 0;\n' +
                '    padding: 0;\n' +
                '  }\n' +
                '  \n' +
                '  /* Hide non-printing elements */\n' +
                '  .no-print {\n' +
                '    display: none !important;\n' +
                '  }\n' +
                '  \n' +
                '  /* Force black text for printing */\n' +
                '  * {\n' +
                '    color: #000 !important;\n' +
                '    -webkit-print-color-adjust: exact;\n' +
                '    print-color-adjust: exact;\n' +
                '  }\n' +
                '}',//这里是分页的关键，渲染到类名为paging时则强制分页。
              scanStyles: false,
              onPrintDialogClose: () => {
                clearInterval(focuser);
                document.querySelector('#printJS-HTML').style.display = 'none';
                this.printArr = [];
              }
            });
            //最后清除dom，不然你的页面会多了这个模板
            document.querySelector('#printJS-HTML').style.display = 'none'
          }, 500)
        });
      } catch (error) {
        console.error('打印渲染失败:', error);
        this.$message.error('打印失败，请稍后重试');
      }
    }
    ,
  }
}
</script>
